// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
    const {
        OPENID
    } = cloud.getWXContext()
    const {
        phone,
        avatarUrl,
        nickName
    } = event
    console.log(phone);
    try {
        // 注册新用户
        const res = await db.collection('users').add({
            data: {
                _openid: OPENID,
                _phone: phone,
                _avatarUrl: avatarUrl,
                _nickName: nickName,
                _createTime: db.serverDate(),
                goodsCount: 0
            }
        })

        return {
            success: true,
            userInfo: {
                _id: res._id,
                phone: phone,
                avatarUrl: avatarUrl,
                nickName: nickName,
                openid: OPENID
            }

        }
    } catch (e) {
        console.error('注册用户失败', e)
        return {
            success: false,
            error: e.message
        }
    }
}